package com.epam.qanda.web.servlet.logged;

import java.io.IOException;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;

import com.epam.qanda.db.model.Answer;
import com.epam.qanda.db.model.Question;
import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.AnswerService;
import com.epam.qanda.db.service.QuestionService;

public class AddAnswerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.sendRedirect(request.getHeader("referer"));
	}

	private String codeTag(String t) {
		String text = t;
		text = text.replaceAll("\\[code\\]",
				"<p><span class='label label-default'>Code</span></p><pre><code>");
		text = text.replaceAll("\\[/code\\]", "</pre></code>");
		return text;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");
		if (user != null) {
			String text = request.getParameter("answerText");

			text = StringEscapeUtils.escapeHtml4(text);		
			text = codeTag(text);
			int qId = Integer.parseInt(request.getParameter("qId"));
			Question question = new QuestionService().read(qId);
			if (question != null) {
				Answer answer = new Answer();
				answer.setLike(0);
				answer.setQuestionId(qId);
				answer.setText(text);
				answer.setTime(new Timestamp(System.currentTimeMillis()));
				answer.setUserId(user.getId());
				new AnswerService().create(answer);
			}
		}
		response.sendRedirect(request.getHeader("Referer"));
	}
}
